package com.mall.web.annotation;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.mall.client.user.SessService;
import com.mall.client.user.UserService;
import com.mall.constant.ReqAttributeKey;
import com.mall.pojo.Sess;
import com.mall.pojo.User;
import com.mall.web.util.CookieUtil;
import com.mall.web.util.WebUtil;

@Aspect
@Component
public class UserLoginMessageAop {
	private static final Logger log = LoggerFactory.getLogger(UserLoginMessageAop.class);

	@Autowired
	private SessService sessService;

	@Autowired
	private UserService userService;

	@Around("@annotation(com.mall.web.annotation.UserLoginMessage)")
	public Object doCheck(ProceedingJoinPoint joinPoint) throws Throwable {

		// 当前登录用户
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();

		Cookie[] cookies = request.getCookies();// 这样便可以获取一个cookie数组
		if (cookies == null || cookies.length <= 0) {
			return joinPoint.proceed();
		}
		String cookieValue = CookieUtil.getCookieValue(request, ReqAttributeKey.COOKIE_FOR_USER);

		if (StringUtils.isBlank(cookieValue)) {
			return joinPoint.proceed();
		}
		String commonOnlyKey = CookieUtil.getCookieValue(request, ReqAttributeKey.COOKIE_FOR_COMMKEYID);
		if (StringUtils.isBlank(commonOnlyKey)) {
			return joinPoint.proceed();
		}
		List<Sess> listSess = sessService.getListBySessionKey(cookieValue,Integer.parseInt(commonOnlyKey));
		if (listSess == null || listSess.isEmpty()) {
			return joinPoint.proceed();
		}

		User user = this.userService.getUserByUserId(listSess.get(0).getUid());
		if (user == null) {
			return joinPoint.proceed();
		}
		WebUtil.setCurrentUserSessionAndCookies(request, response, user);

		return joinPoint.proceed();
	}

}
